// components/custom-tab-bar/index.js
Component({
    data: {
        currentPage: "",
        list: [
            {
                index: 0,
                pagePath: "/pages/index/index",
                iconPath: "/assets/tabbar/home.png",
                selectedIconPath: "/assets/tabbar/home_selected.png",
                text: "首页"
            },
            {
                index: 1,
                pagePath: "/pages/exchange/exchange",
                iconPath: "/assets/tabbar/exchange.png",
                selectedIconPath: "/assets/tabbar/exchange_selected.png",
                text: "兑换"
            },
            {
                index: 2,
                iconPath: "/assets/tabbar/scan_selected.png",
                selectedIconPath: "/assets/tabbar/scan_selected.png",
                text: "扫一扫"
            },
            {
                index: 3,
                pagePath: "/pages/activity/activity",
                iconPath: "/assets/tabbar/activity.png",
                selectedIconPath: "/assets/tabbar/activity_selected.png",
                text: "活动"
            },
            {
                index: 4,
                pagePath: "/pages/mine/mine",
                iconPath: "/assets/tabbar/mine.png",
                selectedIconPath: "/assets/tabbar/mine_selected.png",
                text: "我的"
            }
        ]
    },
    methods: {
        switchTab(e) {
            const index = e.currentTarget.dataset.index;
            const item = this.data.list[index];

            if (index === 2) {
                wx.scanCode({
                    success: res => {
                        console.log("扫码成功", res);
                        wx.showToast({ title: "扫码成功", icon: "success" });
                    },
                    fail: err => {
                        console.log("扫码失败", err);
                        wx.showToast({ title: "扫码失败", icon: "error" });
                    }
                });
                return;
            }

            if (item.pagePath !== this.data.currentPage) {
                wx.switchTab({ url: item.pagePath });
            }
        },
        updateCurrentPages() {
            const pages = getCurrentPages();
            const currentRoute = '/' + pages[pages.length - 1].route;
            this.setData({ currentPage: currentRoute });
        }
    },
    lifetimes: {
        attached() {
            this.updateCurrentPages();
        }
    },
    pageLifetimes: {
        show() {
            this.updateCurrentPages();
        }
    }
});